package com.example.clock_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.clock_demo.common.Result;
import com.example.clock_demo.dto.LoginRequest;
import com.example.clock_demo.dto.LoginResponse;
import com.example.clock_demo.entity.SysUser;
import com.example.clock_demo.mapper.SysUserMapper;
import com.example.clock_demo.service.RedisService;
import com.example.clock_demo.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/auth")
@Api(tags = "认证管理")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisService redisService;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.prefix}")
    private String tokenPrefix;

    @Value("${jwt.expiration}")
    private Long expiration;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()
                    )
            );

            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getUsername, loginRequest.getUsername());
            SysUser user = sysUserMapper.selectOne(wrapper);

            String token = jwtTokenUtil.generateToken(loginRequest.getUsername(), user.getRole());

            LoginResponse response = new LoginResponse();
            response.setToken(token);
            response.setUserId(user.getId());
            response.setUsername(user.getUsername());
            response.setRealName(user.getRealName());
            response.setRole(user.getRole());
            response.setEmployeeNo(user.getEmployeeNo());
            response.setDepartment(user.getDepartment());
            response.setTeam(user.getTeam());

            return Result.success(response);
        } catch (AuthenticationException e) {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/logout")
    @ApiOperation("用户登出")
    public Result<String> logout(HttpServletRequest request) {
        String authHeader = request.getHeader(tokenHeader);
        if (authHeader != null && authHeader.startsWith(tokenPrefix)) {
            String token = authHeader.substring(tokenPrefix.length() + 1);
            redisService.addToBlacklist(token, expiration);
            return Result.success("登出成功");
        }
        return Result.error("未找到有效的令牌");
    }
}